<template>
  <el-dialog
    title="修改处置单位信息"
    :visible.sync="state"
    :modal-append-to-body="false"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeBox">

    <el-form :model="form" :rules="rules" ref="form">

      <el-form-item label="处置单位名称：" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="联系电话：" :label-width="formLabelWidth" prop="contactNumber">
        <el-input v-model="form.contactNumber" :maxlength="11" autocomplete="off"></el-input>
      </el-form-item>

      <el-form-item label="相关资质：" :label-width="formLabelWidth" prop="attrs">
        <el-upload class="oss-upload" ref="upload" action=""
          :multiple="true"
          :file-list="form.attrs"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :auto-upload="false">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </el-upload>
      </el-form-item>

      <el-divider></el-divider>
      <el-row justify='end' align='middle'>
        <el-col :span='24'>
          <el-form-item style='float: right'>
            <el-button @click="cancel('form')">取 消</el-button>
            <el-button type='primary' @click="submit('form')">确 定</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- <el-form-item>
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </el-form-item> -->
    </el-form>
  </el-dialog>
</template>
<script>

export default {
  components: {

  },
  computed: {

  },
  props: ['editItem'],
  data() {
    return {
      formLabelWidth: "120px",
      state: true,

      sigData: null,

      form: {
        name: "",
        contactNumber: "",
        attrs: [],
      },
      rules: {
        name: [{ required: true, message: "请输入处置单位名称", trigger: "blur" }],
        contactNumber: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
        attrs: [{ type: 'array', required: true, message: "请上传相关资质", trigger: "change" }],
      },
    };
  },
  created() {
    this.form = Object.assign({}, this.form, this.editItem);
    this.getSig();
  },
  mounted() {

  },
  methods: {
    closeBox() {
      this.state = false;
      this.$ge.$emit("biz-disposal-unit-change-search");
    },
    cancel(formName) {
      this.state = false;
      this.$refs[formName].resetFields();
    },
    handleRemove(file, fileList) {
      this.form.attrs = fileList;
    },
    handleChange(file, fileList) {
      //类型（jpg, png）和大小(2M 以内)
      // const isJPG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png';
      const isLt2M = file.raw.size / 1024 / 1024 < 500;
      // if (!isJPG) {
      //     this.$message.error('上传头像图片只能是 jpg 或者 png 格式!');
      //     return;
      // }
      if (!isLt2M) {
          this.$message.error('单个文件大小不能超过 500MB!');
          return;
      }
      // if(isJPG && isLt2M) {
      //   this.fileList.push(file);
      // }
      this.form.attrs.push(file);
      return false;
    },
    getSig() {
      this.$get("/oss/getUploadOssSignature")
        .then((result) => {
          if (result.code == 200 && result.data) {
            this.sigData = result.data;
          }
        })
        .catch((error) => {
          this.sigData = null;
        });
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$WLoading();
          var param = Object.assign({}, this.form, param);
          //上传相关资质
          param.attrs = this.submitUpload(param.attrs);

          this.$postJson("/biz-disposal-unit/update", param)
            .then((result) => {
              if (result.code == 200) {
                this.$message.success(result.msg);

                //关闭弹框并刷新列表
                this.closeBox(formName);
              } else this.$message.error(result.msg);
              this.$cancelLoading();
            })
            .catch((error) => {
              //添加用户异常
              this.$message.error("添加失败");
              this.$cancelLoading();
            });
        } else {
          console.log("填写有误！");
          return false;
        }
      });
    },
    submitUpload(allAttr) {
      
      let sigData = this.sigData;//提前请求拿到的签名信息

      let nowAllAttr = [];
      if(!allAttr || allAttr.length == 0) 
        return nowAllAttr;

      allAttr.forEach(element => {
        let ossData = new FormData()//创建oss数据对象
        ossData.append('name', element.name)
        let keyValue = 'ep/web/' + this.uuid() + '::' + element.name
        ossData.append('key', keyValue)
        ossData.append('policy', sigData.policy)
        ossData.append('OSSAccessKeyId', sigData.accessId)
        ossData.append('success_action_status', 200)
        ossData.append('Signature', sigData.signature)
        ossData.append('file', element.raw)

        this.$postFormData(sigData.ossDomain, ossData)
          .then((result) => {})
          .catch((error) => {});

        nowAllAttr.push({
          name: element.name,
          url: sigData.ossDomain +'/'+ keyValue,
          size: element.size,
        })
      });

      return nowAllAttr;
    },

  },
};
</script>

<style>
.el-select {
  width: 100%;
}
.vue-treeselect__input {
  border: 0 !important;
}
/* 上传样式 start */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/* 上传样式 end */
</style>
